package com.study.rcp.framework.treeview;

import java.util.ArrayList;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.study.rcp.framework.core.Activator;
import com.study.rcp.framework.view.AutoGeneratorCodeView;

public class NavigationView extends ViewPart {
	public NavigationView() {
	}

	public static final String ID = "rcpframework.navigationView";
	private TreeViewer viewer;

	class TreeObject {
		private String name;
		private TreeParent parent;
		protected String image;

		public TreeObject(String name,String image) {
			this.name = name;
			this.image=image;
		}

		public String getName() {
			return name;
		}

		public void setParent(TreeParent parent) {
			this.parent = parent;
		}

		public TreeParent getParent() {
			return parent;
		}
		
		public String getImage() {
			return image;
		}

		public void setImage(String image) {
			this.image = image;
		}

		public String toString() {
			return getName();
		}
	}

	@SuppressWarnings("rawtypes")
	class TreeParent extends TreeObject {

		private ArrayList children;

		public TreeParent(String name,String image) {
			super(name,image);
			children = new ArrayList();
		}

		@SuppressWarnings("unchecked")
		public void addChild(TreeObject child) {
			children.add(child);
			child.setParent(this);
		}

		public void removeChild(TreeObject child) {
			children.remove(child);
			child.setParent(null);
		}

		@SuppressWarnings("unchecked")
		public TreeObject[] getChildren() {
			return (TreeObject[]) children.toArray(new TreeObject[children
					.size()]);
		}

		public boolean hasChildren() {
			return children.size() > 0;
		}
	}

	class ViewContentProvider implements IStructuredContentProvider,
			ITreeContentProvider {

		public void inputChanged(Viewer v, Object oldInput, Object newInput) {
		}

		public void dispose() {
		}

		public Object[] getElements(Object parent) {
			return getChildren(parent);
		}

		public Object getParent(Object child) {
			if (child instanceof TreeObject) {
				return ((TreeObject) child).getParent();
			}
			return null;
		}

		public Object[] getChildren(Object parent) {
			if (parent instanceof TreeParent) {
				return ((TreeParent) parent).getChildren();
			}
			return new Object[0];
		}

		public boolean hasChildren(Object parent) {
			if (parent instanceof TreeParent)
				return ((TreeParent) parent).hasChildren();
			return false;
		}
	}

	class ViewLabelProvider extends LabelProvider {

		public String getText(Object obj) {
			return obj.toString();
		}

		public Image getImage(Object obj) {
			String imageKey = ISharedImages.IMG_OBJ_ELEMENT;
			if (obj instanceof TreeParent)
				imageKey= ((TreeParent)obj).getImage();
//				imageKey = ISharedImages.IMG_OBJ_FOLDER;
			else if (obj instanceof TreeObject)
				imageKey= ((TreeObject)obj).getImage();
//				imageKey = ISharedImages.IMG_OBJ_FOLDER;
//			return PlatformUI.getWorkbench().getSharedImages()
//					.getImage(imageKey);
			return AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID,
					imageKey).createImage();
		}
	}

	/**
	 * We will set up a dummy model to initialize tree heararchy. In real code,
	 * you will connect to a real model and expose its hierarchy.
	 */
	private TreeObject createDummyModel() {
		
		TreeParent p1 = new TreeParent("控制台","icons/folder22.png");
		TreeParent p12 = new TreeParent("开发工具","icons/folder9.png");
		p1.addChild(p12);
		TreeObject to2 = new TreeObject("代码生成","icons/icon66.png");
		
		p12.addChild(to2);

//		TreeObject to4 = new TreeObject("Inbox");
//		TreeParent p2 = new TreeParent("other@aol.com");
//		p2.addChild(to4);
		TreeParent root = new TreeParent("","icons/folder22.png");
		root.addChild(p1);
		return root;
	}

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	public void createPartControl(Composite parent) {
//		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL
//				| SWT.BORDER);
		viewer =TreeViewerFactory.create(parent, SWT.MULTI | SWT.VIRTUAL);
		Tree tree = viewer.getTree();
		tree.setTouchEnabled(true);
		tree.setHeaderVisible(true);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setInput(createDummyModel());
		final IWorkbenchWindow window = this.getViewSite().getWorkbenchWindow();
		viewer.addDoubleClickListener(new IDoubleClickListener() {

			@Override
			public void doubleClick(DoubleClickEvent arg0) {
				// TODO Auto-generated method stub
				ISelection selection = arg0.getSelection();    //与此ISelection selection = treeViewer.getSelection();  
                // 得到选中的项，注意方法是将得到的选项转换成 IStructuredSelection，在调用 getFirstElement 方法  
                Object object = ((IStructuredSelection) selection).getFirstElement();  
                // 再将对象转为实际的树节点对象  
                if(object instanceof TreeParent) {
                	TreeParent element=(TreeParent) object;
                	 // 处理展开/收缩子菜单  
                    if(element.hasChildren()){  
                        //获取展开状态  
                        if(viewer.getExpandedState(element))  
                        	viewer.collapseToLevel(element, 1);  
                        else   
                        	viewer.expandToLevel(element, 1);    
                    }  
                }else{
                	int instanceNum = 0;
    				if (window != null) {
    					try {
    						window.getActivePage().showView(
    								AutoGeneratorCodeView.ID,
    								Integer.toString(instanceNum++),
    								IWorkbenchPage.VIEW_ACTIVATE);
    					} catch (PartInitException e) {
    						MessageDialog.openError(window.getShell(), "Error",
    								"Error opening view:" + e.getMessage());
    					}
    				}
                }
				
			}
		});

	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}
}